<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <!-- 是否为经营管理部初审 -->
    <el-form class="tl-form" ref="dealform" :model="model" :rules="rules" label-width="120px" v-if="extraParam==='CSApproval'">
      <br>
      <br>
      <el-row>
        <el-col :span="12">
          <el-form-item label="审批部门" prop="approvaldepartment">
            <el-select v-model="model.approvaldepartment" filterable collapse-tags clearable multiple>
              <el-option v-for="item in codeModel.approvalDepartmentList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || disableSave">
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>1、【采购合同申请】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目" prop="projectid" :required="true" :rules="rules.validateRequire">
            <el-input v-model="model.dispprojectid" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmProjectRefDialog" v-if="!disableEditSubmit && !disableSave"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已付款金额" prop="totalpaymoney">
            <el-input-number v-model="model.totalpaymoney" disabled controls-position="right" :step="1" :min="0" :precision="2" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="采购申请单" prop="purchaseapplyid" :required="true" :rules="rules.validateRequire">
            <el-input v-model="model.purchaseapplyid" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openpmPurchaseApplyRefDialog" v-if="!(disableEditSubmit || disableSave)"></el-button>
            </el-input>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购申请金额">
            <el-input-number v-model="model.purchaseapplymoney" :disabled="true" :precision="2" controls-position="right" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contracttype" :rules="rules.validateRequire">
            <el-select v-model="model.contracttype" filterable clearable>
              <el-option v-for="item in codeModel.contracttypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同所属部门" prop="purchasedeptname" :required="true" :rules="rules.validateRequire">
            <tl-ref-dept v-model="model.purchasedeptcode" :initDisplayData.sync="model.purchasedeptname" dataType="code" :singleSelect="true" @confirm="onSelectPurchaseDept" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同所属组织" prop="purchaseorgname">
            <el-input v-model="model.purchaseorgname" :readonly="true" class="is-disabled"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractname" :rules="rules.validateRequire">
            <el-input v-model="model.contractname"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同日期" prop="contractdate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.contractdate" type="date" placeholder="合同日期" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
                    <el-form-item label="合同编号" prop="contractcode">
                        <el-input v-model="model.contractcode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                </el-col> -->
      </el-row>
      <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label="合同类型" prop="contracttype" :rules="rules.validateRequire">
                        <el-select v-model="model.contracttype" filterable clearable>
                            <el-option v-for="item in codeModel.contracttypeList" :key="item.code" :label="item.name" :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同金额" prop="contractmoney" :rules="rules.validateRequire">
            <el-input-number v-model="model.contractmoney" controls-position="right" :step="1" :min="0" :precision="2" style="width:95%"></el-input-number>
            <span>元</span>
          </el-form-item>
        </el-col>
        <el-col :span="11" :offset="1">
          <el-alert title="提示：若本次合同金额为负值，则项目采购合同金额会减去相应值。" type="warning" :closable="false">
          </el-alert>
        </el-col>
      </el-row>
      <el-row>

      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="合同描述" prop="contractcontent">
            <el-input v-model="model.contractcontent" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="收件人" prop="receiver" :rules="rules.validateRequire">
            <el-input v-model="model.receiver"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收件人电话" prop="phone" :rules="rules.validateRequire">
            <el-input v-model="model.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="回寄地址" prop="postal" :rules="rules.validateRequire">
            <el-input v-model="model.postal" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="快递单号" prop="couriernumber" v-show="model.state == '9' || model.couriernumber != null">
            <el-input v-model="model.couriernumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="快递方式" prop="courier" v-show="model.state == '9' || model.couriernumber != null">
            <el-select v-model="model.courier" filterable clearable>
              <el-option v-for="item in codeModel.courierList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="model.description" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>2、【单据】相关信息</span></el-divider>
        </el-col>
      </el-row> -->
      <el-collapse>
        <el-collapse-item title="【单据】相关信息">
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请公司" prop="orgname">
                <el-input v-model="model.orgname" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请部门" prop="deptname" :required="true" :rules="rules.validateRequire">
                <tl-ref-dept v-model="model.deptcode" :initDisplayData.sync="model.deptname" :disabled="true" dataType="code" :singleSelect="true" @confirm="onSelectDept" :externalQueryParam="{qry_enabled:1}"></tl-ref-dept>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申请人工号" prop="usercode">
                <el-input v-model="model.usercode" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人姓名" prop="username" :required="true" :rules="rules.validateRequire">
                <tl-ref-user v-model="model.usercode" :initDisplayData.sync="model.username" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单据日期" prop="docdate">
                <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="提交时间" prop="submitdate">
                <el-date-picker v-model="model.submitdate" type="datetime" placeholder="提交时间" value-format="yyyy-MM-dd HH:mm:ss" :readonly="true" class="is-disabled"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="审批流程" prop="flowid">
                <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-input v-model="model.dispstate" :readonly="true" class="is-disabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <tl-approval-history ref="history" sourceType="PmPurchaseContract" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit" v-if="uiOperateState<=2">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <tl-attachment ref="attachmentRef" sourceType="PmPurchaseContract" btnTitle="合同文件" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit"></tl-attachment>
      <tl-attachment ref="attachmentSignRef" sourceType="PmSignPurchaseContract" :sourceId="model.id" btnTitle="合同扫描件" :disabled="disableAttachment" :editable="stateEdit"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableDelApproval" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlpm-project-ref ref="pmProjectRef" @confirm="getpmProjectRefData" :isSingleSelect="true" :externalQueryParam="{qry_processflag:'1' }"></tlpm-project-ref>
    <tlpm-purchase-apply-ref ref="pmPurchaseApplyRef" @confirm="getpmPurchaseApplyRefData" :isSingleSelect="true" :externalQueryParam="{qry_state:'9'}"></tlpm-purchase-apply-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlpmProjectRef from '@/views/ProjectManage/pmProject/refList'
import tlpmPurchaseApplyRef from '@/views/ProjectManage/pmPurchaseApply/refList'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlpmProjectRef, tlpmPurchaseApplyRef },
  data() {
    return {
      moduleTitle: '采购合同申请',
      urlPrefix: '/pm/purchaseContract/',
      disableAttachmentButton: true,
      extraParam: '',
      url: {
        // 额外的url
        queryCodeList: '/pm/purchaseContract/dataCodeList',
        queryOrgByDeptId: '/pm/resourceArchives/queryOrgByDeptId'
      }
    }
  },
  props: {
    projectId: {
      type: [Number, String],
      default: function() {
        return ''
      }
    },
    editFlag: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    doApprovalDepart(resolve, reject) {
      const { approvaldepartment, deptcode, id } = this.model
      if (approvaldepartment !== null && approvaldepartment !== undefined) {
        const param = {
          approvaldepartment: approvaldepartment,
          deptcode: deptcode,
          CSApproval: 1,
          id: id
        }
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
          .catch(err => {
            this.$tap.alert('保存审批部门信息失败，请联系系统管理员', 'warning')
            reject()
          })
      } else {
        resolve()
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        // if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
        //     this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        // }
        // this.$set(this.model, 'orgcode', this.org.code)
        // this.$set(this.model, 'orgname', this.org.name)
        // this.$set(this.model, 'deptcode', this.dept.code)
        // this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
      }
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    loaded() {
      // 页面加载完毕执行
      if (this.isAdd === false && this.disableEditSubmit === true) {
        var params = {
          sourceType: 'PmPurchaseContract',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
              this.$emit('refresh')
            }
          }
        })
      }
    },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then(res => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.disableAttachmentButton = false
            this.isAdd = false
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    /** 打开项目参照 */
    openpmProjectRefDialog() {
      this.$refs.pmProjectRef.visible = true
    },
    /** 获取项目参数数据 */
    getpmProjectRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'projectid', selectionRow.id)
      this.$set(this.model, 'dispprojectid', selectionRow.name)
      this.$set(this.model, 'purchaseapplymoney', selectionRow.purchasemoney)
      this.$set(this.model, 'totalpaymoney', selectionRow.purchasepaymentmoney)
      // 采购申请单信息来源于项目 以项目所属部门信息为准
      this.$set(this.model, 'deptcode', selectionRow.deptcode)
      this.$set(this.model, 'deptname', selectionRow.deptname)
      this.$set(this.model, 'orgcode', selectionRow.orgcode)
      this.$set(this.model, 'orgname', selectionRow.orgname)
    },
    /** 打开采购申请单参照 */
    openpmPurchaseApplyRefDialog() {
      this.$refs.pmPurchaseApplyRef.visible = true
    },
    /** 获取采购申请单参数数据 */
    getpmPurchaseApplyRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'purchaseapplyid', selectionRow.id)
      this.$set(this.model, 'projectid', selectionRow.projectid)
      this.$set(this.model, 'dispprojectid', selectionRow.dispprojectid)
      this.$set(this.model, 'purchaseapplymoney', selectionRow.applymoney)
      // 采购申请单信息来源于项目 以项目所属部门信息为准
      this.$set(this.model, 'deptcode', selectionRow.deptcode)
      this.$set(this.model, 'deptname', selectionRow.deptname)
      this.$set(this.model, 'orgcode', selectionRow.orgcode)
      this.$set(this.model, 'orgname', selectionRow.orgname)
    },
    onSelectPurchaseDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, fullname } = selectedDept
      this.$set(this.model, 'purchasedeptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then(res => {
        if (res.success) {
          const { code: orgCode, name: orgName } = res.result
          this.$set(this.model, 'purchaseorgcode', orgCode)
          this.$set(this.model, 'purchaseorgname', orgName)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, fullname } = selectedDept
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then(res => {
        if (res.success) {
          const { code: orgCode } = res.result
          this.$set(this.model, 'orgcode', orgCode)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    beforeSubmit() {
      const { purchaseapplymoney, contractmoney } = this.model
      if (purchaseapplymoney && contractmoney && contractmoney > purchaseapplymoney) {
        this.$tap.alert('合同金额不能高于采购申请金额！', 'warning')
        return false
      }
      return true
    },
    /** 提交审批前*/
    beforeApproval() {
      if (this.$refs.attachmentRef.fileList.length === 0) {
        this.$tap.alert('请上传合同附件！', 'warning')
        this.submitLoading = false
        return false
      }
      return true
    }
  }
}
</script>
